package com.bkgy.controller.continuousSlantingHistory.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.bkgy.controller.continuousSlantingHistory.dao.ContinuousDao;
import com.bkgy.controller.continuousSlantingHistory.dto.ContinuousDto;
import com.bkgy.controller.continuousSlantingHistory.entity.Continuous;
import com.bkgy.controller.continuousSlantingHistory.service.ContinuousSlantingHistoryService;
import com.bkgy.controller.continuousSlantingHistory.utils.FieldMappingUtil;
import com.bkgy.controller.continuousSlantingHistory.utils.TimeTransUtils;
import com.bkgy.sys.common.entity.ResultData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.lang.reflect.Method;
import java.util.*;
import java.util.stream.Collectors;


/**
 * 连退跑偏历史服务实现类
 */
@Service
public class ContinuousSlantingHistoryServiceImpl  implements ContinuousSlantingHistoryService {

    @Autowired
    private ContinuousDao continuousDao;
    @Autowired
    private TimeTransUtils timeTransUtils;

    @Override
    public ResultData<Map<String, Object>> getSteelPositionTableData(JSONObject jsonObjec) {
        Map<String, Object> result = new HashMap<>();
        try {
            String startTime = jsonObjec.getString("startTime");
            String endTime = jsonObjec.getString("endTime");

            if (!(StringUtils.hasText(startTime) && StringUtils.hasText(endTime))) {
                return ResultData.ResultDataFaultSelf("时间参数没有传", null);
            }

            startTime = timeTransUtils.timeToString(startTime);
            endTime = timeTransUtils.timeToString(endTime);

            Continuous continuous = continuousDao.selectAvgAndStdData(startTime, endTime);
            ContinuousDto dto =new ContinuousDto();
            if(continuous!=null){
                dto = continuousToDto(continuous);
            }

            // 构建纠偏位置行 和 带钢位置行
            result.put("dataList", Arrays.asList(
                    new TreeMap<>(buildCorrectionRow(dto)),
                    new TreeMap<>(buildSteelStripRow(dto))
                    )
            );
        } catch (Exception e) {
            e.printStackTrace();
            return ResultData.ResultDataFaultSelf("查询失败", null);
        }
        return ResultData.ResultDataSuccess(result);
    }

    @Override
    public ResultData<ContinuousDto> getCpcRoll(JSONObject jsonObjec) {
        try {
            String startTime = jsonObjec.getString("startTime");
            String endTime = jsonObjec.getString("endTime");

            if (!(StringUtils.hasText(startTime) && StringUtils.hasText(endTime))) {
                return ResultData.ResultDataFaultSelf("时间参数没有传", null);
            }

            startTime = timeTransUtils.timeToString(startTime);
            endTime = timeTransUtils.timeToString(endTime);

            List<Continuous> contList = continuousDao.selectCountByDate(startTime, endTime);
            List<ContinuousDto> dtos = contList.stream()
                    .map(this::continuousToDto)
                    .collect(Collectors.toList());

            return ResultData.ResultDataSuccess(dtos, dtos.size());
        } catch (Exception e) {
            e.printStackTrace();
            return ResultData.ResultDataFaultSelf("查询失败", null);
        }
    }

    @Override
    public ContinuousDto continuousToDto(Continuous continuous) {
        ContinuousDto dto = new ContinuousDto();
        dto.setExtid(continuous.getExtid());
        dto.setCreate_time(continuous.getCreateTime());
        // 使用工具类自动拷贝属性
        FieldMappingUtil.copyProperties(continuous, dto);

        return dto;
    }

    private Map<String, Object> buildCorrectionRow(ContinuousDto dto) {
        return buildRow(dto, "", "纠偏缸位置");
    }

    private Map<String, Object> buildSteelStripRow(ContinuousDto dto) {
        return buildRow(dto, "strip_", "带钢位置");
    }

    private Map<String, Object> buildRow(ContinuousDto dto, String suffix, String rowName) {
        Map<String, Object> row = new LinkedHashMap<>();
        row.put("name", rowName);

        // 处理普通CPC字段
        for (int i = 1; i <= 17; i++) {
            if (i != 9) {
                addFieldToRow(row, dto, "Cpc" + i + "_" + suffix);
            }
        }

        // 处理CPC9字段
        for (int j = 0; j <= 8; j++) {
            addFieldToRow(row, dto, "Cpc9_" + j + "_" + suffix);
        }

        // 处理EPC字段
        for (int k = 1; k <= 2; k++) {
            addFieldToRow(row, dto, "Epc" + k + "_" + suffix);
        }

        return row;
    }
    private void addFieldToRow(Map<String, Object> row, ContinuousDto dto, String prefix) {
        try {
            Method avgMethod = dto.getClass().getMethod("get" + prefix + "avg");
            Object avgValue = avgMethod.invoke(dto);
            if (avgValue != null) {
                row.put(prefix + "avg", avgValue);
            }

            if(prefix.contains("Cpc")&&!prefix.contains("strip")){
                Method maxMethod = dto.getClass().getMethod("get" + prefix + "max");
                Object maxValue = maxMethod.invoke(dto);
                if (maxValue != null) {
                    row.put(prefix + "max", maxValue);
                }

                Method minMethod = dto.getClass().getMethod("get" + prefix + "min");
                Object minValue = minMethod.invoke(dto);
                if (minValue != null) {
                    row.put(prefix + "min", minValue);
                }
            }
            // 获取STD值
            Method stdMethod = dto.getClass().getMethod("get" + prefix + "std");
            Object stdValue = stdMethod.invoke(dto);
            if (stdValue != null) {
                row.put(prefix + "std", stdValue);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
